package com.wangbo.multi;

import com.wangbo.multi.exception.CustomException;
import com.wangbo.multi.exception.enums.BadRequestExceptionEnum;
import com.wangbo.multi.exception.enums.ServerExceptionEnum;
import com.wangbo.multi.model.ResultObj;
import com.wangbo.multi.util.ResultObjUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Package: com.company.scaffold.exception.handler
 * @Author: Mr.Waves
 * @Date: 2020-03-09 10:43
 * @Description: 全局异常统一处理类
 **/
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * @ExceptionHandler采取就近原则，会从类型最接近的Exception子类开始匹配
     * 500
     */
    @ExceptionHandler(value = Exception.class)
    public ResultObj exceptionHandler(Exception e) {
        log.error("【未知异常】: {}", e.getLocalizedMessage(), e);
        return ResultObjUtil.error(ServerExceptionEnum.UNKNOWN_EXCEPTION);
    }

    /**
     * Custom异常处理
     */
    @ExceptionHandler(value = CustomException.class)
    public ResultObj exceptionHandler(CustomException e) {
        log.error("【业务异常】: {}", e.getMessage(), e);
        return ResultObjUtil.error(e.getCode(), e.getMessage());
    }

    /**
     * validation
     */
    @ExceptionHandler(BindException.class)
    public ResultObj handleError(BindException e) {
        BindingResult bindingResult = e.getBindingResult();
        String message = bindingResult.getFieldErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining(","));
        log.error("【参数校验】: {}", message, e);
        return ResultObjUtil.error(BadRequestExceptionEnum.INVALID_PARAMETER, message);
    }

}
